//
//  CourseController.m
//  TrainTree
//
//  Created by wanghui on 2017/8/24.
//  Copyright © 2017年 YouYeShu. All rights reserved.
//

#import "CourseController.h"
#import "CourseTopCell.h"
#import "CourseVideoCell.h"
#import "TopTabView.h"
#import "CourseSectionHeaderView.h"
#import "CourseDetailController.h"
#import "SearchController.h"
#import "CourseRequestManager.h"
#import "CourseListModel.h"
#import "CourseAudioVideoController.h"
#import "StudyRequestManager.h"
@interface CourseController ()<UITableViewDelegate,UITableViewDataSource,SectionHeaderViewDelegate,TopTabViewDelegate,SelectCourseDelegate,BannerToNextPageDelegate>
{
    TopTabView *_topTabView;// 顶部按钮view
    CourseSectionHeaderView *_headerView;// sectionHeaderView
    PageType _type;// 当前类
    UIColor *_typeColor;// 主题颜色
    UIButton *_sectionBtn;// 组头按钮
    UILabel *_sectionLabel;// 组头文字
    UILabel *_sectionLine;// 组头竖线
    NSString *_sectionImg;// 组头照片
}
@property (strong, nonatomic)UITableView *tableView;
/**轮播图*/
@property(nonatomic,strong) NSArray *bannerArray;
/**数据数组*/
@property(nonatomic,strong) NSArray *lessonListArray;
/**类型字符串*/
@property(nonatomic,copy) NSString *typeStr;
/**选中数组*/
@property(nonatomic,strong) NSMutableArray *selectArray;
/**主题列表数组*/
@property(nonatomic,strong) NSMutableArray *themeArray;

 
@end

@implementation CourseController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (![Session isLogin]) {
        [Login presentLoginPage];
    }
    [StudyRequestManager getStudyType:StudyTypeRequired Response:^(id JSONData, NSError *error, NSURLSessionDataTask *dataTask) {}];


}

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.navigationView.title = @"课程";
//    [Login presentLoginPage];
    [self.navigationView.leftBtn addTarget:self action:@selector(searchBtnClick ) forControlEvents:UIControlEventTouchUpInside];

    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 60, ScreenWidth, ScreenHeight - 60 - 49) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"CourseTopCell" bundle:nil] forCellReuseIdentifier:@"CourseTopCell"];
     
    // 请求轮播图数据
    [CommonRequestManager getBannerListResponse:^(id JSONData, NSError *error, NSURLSessionDataTask *dataTask) {

    }];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDataWithSlideshow) name:@"reloadDataWithSlideshow" object:nil];
//    self.bannerArray = [BannerData shareBannerData].bannerArray;

    self.selectArray = [[NSMutableArray alloc] initWithArray: @[@"1",@"0",@"0",@"0",@"0",@"0",@"0",@"0"]];
    WeakSelf(ws);
    [CourseRequestManager getThemeListResponseBlock:^(id JSONData, NSError *error, NSURLSessionDataTask *dataTask) {
        ws.themeArray = JSONData[@"d"];
        if (ws.themeArray.count > 0) {
            [ws requestLessonListDataWithThemeId:ws.themeArray[0][@"themeId"]];
        }
    }];

    _typeColor = universeColor;

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess) name:@"loginSuccess" object:nil];

}
#pragma mark - 登录成功请求数据
- (void)loginSuccess
{
    WeakSelf(ws);
    [CourseRequestManager getThemeListResponseBlock:^(id JSONData, NSError *error, NSURLSessionDataTask *dataTask) {
        ws.themeArray = JSONData[@"d"];
        if (ws.themeArray.count > 0) {
            [ws requestLessonListDataWithThemeId:ws.themeArray[0][@"themeId"]];
        }
    }];
    [CommonRequestManager getBannerListResponse:^(id JSONData, NSError *error, NSURLSessionDataTask *dataTask) {

    }];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"loginSuccess" object:nil];

}

#pragma  mark 轮播图
- (void)reloadDataWithSlideshow
{
    self.bannerArray = [BannerData shareBannerData].bannerArray;

    NSIndexSet *indexSet = [[NSIndexSet alloc]initWithIndex:0];
    [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationFade];

    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"reloadDataWithSlideshow" object:nil];
}
#pragma  mark - 请求数据
- (void)requestLessonListDataWithThemeId:(NSString *)themeId
{
    WeakSelf(ws);
    [CourseRequestManager getLessonListWithThemeId:themeId responseBlock:^(id JSONData, NSError *error, NSURLSessionDataTask *dataTask) {
        ws.lessonListArray = nil;
        ws.lessonListArray = JSONData[@"d"];
        NSMutableArray *tmpArray = [[NSMutableArray alloc]init];
        for (NSDictionary *dic in ws.lessonListArray) {
            CourseListModel *model = [CourseListModel mj_objectWithKeyValues:dic];
            [tmpArray addObject:model];
        }
        ws.lessonListArray = [tmpArray copy];

        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:1];
        [self.tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationFade];

        [ws createTopTabView];
    }];
}

#pragma mark - 搜索
- (void)searchBtnClick
{
    self.hidesBottomBarWhenPushed = YES;
    SearchController *searchVc = [[SearchController alloc]init];
    [self.navigationController pushViewController:searchVc animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

- (void)createTopTabView
{
    _topTabView = [LoadXibTool loadViewFromXibName:@"TopTabView"];
    _topTabView.frame = CGRectMake(0, 60, ScreenWidth, 42);
    _topTabView.alpha = 0;
    _topTabView.delegate = self;
    _topTabView.selectArray = self.selectArray;
    _topTabView.themeArray = self.themeArray;

    [self.view addSubview:_topTabView];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat minAlphaOffset = 140;
    CGFloat maxAlphaOffset = 220;
    CGFloat offset = scrollView.contentOffset.y;
    CGFloat alpha = (offset - minAlphaOffset) / (maxAlphaOffset - minAlphaOffset);
    _topTabView.alpha = alpha;
    _headerView.alpha = 1 - alpha;

}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        _headerView = [LoadXibTool loadViewFromXibName:@"CourseSectionHeaderView"];
        _headerView.delegate = self;
        _headerView.selectArray = self.selectArray;
        _headerView.themeArray = self.themeArray;

        return _headerView;
    } else{
        return nil;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
       return 81.0f;
    }else{
        return 0.0f;
    }
}

#pragma mark - tableView DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else{
        return self.lessonListArray.count;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {

        CGFloat height  = (ScreenWidth * 160 / 375);

        return  height;
    } else {

        return 138.0f;
    }

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        CourseTopCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CourseTopCell"];
         
        cell.delegate = self;
        [cell configWithArray:self.bannerArray];
        return  cell;
    } else {
        CourseVideoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CourseVideoCell"];

        if (!cell) {
            cell = [LoadXibTool loadViewFromXibName:@"CourseVideoCell"];
        }
        if(self.lessonListArray.count > 0) {

            cell.delegate = self;
            if (_type == PageTypeUniverse) {
                cell.verticalLine.backgroundColor = universeColor;
                _typeColor = universeColor;
            } else if (_type == PageTypeLeader) {
                cell.verticalLine.backgroundColor = leaderColor;
                _typeColor = leaderColor;
            } else if (_type == PageTypeOperation) {
                cell.verticalLine.backgroundColor = operationColor;
                _typeColor = operationColor;
            } else if (_type == PageTypeHr) {

                cell.verticalLine.backgroundColor = hrColor;
                _typeColor = hrColor;
            } else if (_type == PageTypeFinance) {
                cell.verticalLine.backgroundColor = financeColor;
                _typeColor = financeColor;
            } else if (_type == PageTypeLec) {
                cell.verticalLine.backgroundColor = lecColor;
                _typeColor = lecColor;
            }

            [cell configWithData:self.lessonListArray[indexPath.row] lineColor:_typeColor];
        }

        return cell;
    }
}

#pragma  mark - 每条CollectionView的点击方法
- (void)jumpToCourseDetail:(NSString *)lessonId
{
        // 根据type 跳转到指定类型的课程详情页
    self.hidesBottomBarWhenPushed = YES;
    CourseDetailController *vc = [[CourseDetailController alloc]init];
    vc.lessonId = lessonId;
    [self.navigationController pushViewController:vc animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}

#pragma mark - 根据轮播图type跳往课程详情或者知识点详情
- (void)bannerToNextPageWithType:(NSString *)type lessonId:(NSString *)lessonId
{
    if ([type intValue] == 0) {// 跳往课程
        self.hidesBottomBarWhenPushed = YES;
        CourseDetailController *vc = [[CourseDetailController alloc]init];
        vc.lessonId = lessonId;
        [self.navigationController pushViewController:vc animated:YES];
        self.hidesBottomBarWhenPushed = NO;
    } else if ([type intValue] == 1) {// 跳往知识点
        self.hidesBottomBarWhenPushed = YES;
        CourseAudioVideoController *vc = [[CourseAudioVideoController alloc]init];
        vc.pointId = lessonId;
        [self.navigationController pushViewController:vc animated:YES];
        self.hidesBottomBarWhenPushed = NO;
    } else{

    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

}
#pragma mark - 顶部按钮行点击事件代理方法
- (void)topTabViewTouch:(NSString *)Id index:(NSInteger)index
{
    for (int i = 0; i < _headerView.selectArray.count; i++) {
        if(index == i){
            _headerView.selectArray[i] = @"1";
        }else{
            _headerView.selectArray[i] = @"0";
        }
    }
    self.selectArray = _headerView.selectArray;
    NSLog(@"top的数组%@",self.selectArray);

    NSLog(@"下划线的的数组%@",_headerView.selectArray);
    [_headerView.collectionView reloadData];

    // 刷新，回来尝试 self.tableView reloadData
    [self requestLessonListDataWithThemeId:Id];

}
#pragma mark - Section头点击事件的代理方法
- (void)sectionHeaderChangeUIWith:(NSString *)Id index:(NSInteger )index
{
    for (int i = 0; i < _topTabView.selectArray.count; i++) {
        if(index == i){
            _topTabView.selectArray[i] = @"1";
        }else{
            _topTabView.selectArray[i] = @"0";
        }
    }
    [_topTabView.collectionView reloadData];
    self.selectArray = _topTabView.selectArray;
    _type = (PageType)index % 6;

    [self requestLessonListDataWithThemeId:Id];

}

#pragma mark - 懒加载

- (NSMutableArray *)themeArray
{
    return _themeArray ?: (_themeArray = [NSMutableArray array]);
}
- (NSArray *)bannerArray
{
    return _bannerArray ?: (_bannerArray = [[NSArray alloc] init]);
}

- (NSArray *)lessonListArray
{
    return _lessonListArray ?: (_lessonListArray = [[NSArray alloc]init]);
}
- (NSMutableArray *)selectArray
{
    return _selectArray ?: (_selectArray = [NSMutableArray array]);
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
